import { uploadDocApi } from '@/api';
import React, { useRef } from 'react';

interface UploadImgProps {
    onUpload: (file: File) => void;
    updata: () => void;
    dirid?: string;
}

const UploadImg: React.FC<UploadImgProps> = ({onUpload, updata, dirid }) => {
    const fileInputRef = useRef<HTMLInputElement>(null);

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            handleHttpUpload(file)
            onUpload(file)
        }
    };

    const handleHttpUpload = async (file: any) => {
        let entity: any = {
            dirid: dirid,
            filename: file.name,
            filesize: file.size,
            filetype: file.type,
            id: file.uid
        }
        try {
            const { data, code } = await uploadDocApi(file, entity)
            if (code == 200) {
                updata();
            }
        } catch (error) {
            // options.onError(error as any)
        }
    }

    const handleCardClick = () => {
        fileInputRef.current?.click();
    };

    return (
        <div
            style={{
                border: '1px dashed #ccc',
                borderRadius: 8,
                padding: 24,
                textAlign: 'center',
                cursor: 'pointer',
                background: '#fafafa',
            }}
            onClick={handleCardClick}
        >
            <input
                type="file"
                accept="image/*"
                ref={fileInputRef}
                style={{ display: 'none' }}
                onChange={handleFileChange}
            />
            <div style={{ marginTop: 12, color: '#888' }}>上传图片</div>
        </div>
    );
};

export default UploadImg;